const axios = require("axios");

function handleResponseError(err) {
  // 如果是取消的请求不触发错误
  if (axios.isCancel(err)) return new Promise(() => {});
  const errType = typeof err;
  if (err && errType === "string") {
    return new Promise(() => {});
  }
  if (errType === "object") {
    err = "请求错误";
  }
  return Promise.reject(err);
}

function runInterceptors(instance) {
  const requestUse = instance.interceptors.request.use.bind(
    instance.interceptors.request
  );
  const responsetUse = instance.interceptors.response.use.bind(
    instance.interceptors.response
  );

  // 添加token
  requestUse((config) => {
    const xToken = global.xToken;
    xToken && (config.headers["x-token"] = xToken);
    return config;
  });

  // 设置post的data不为空
  requestUse((config) => {
    if (config.method === "post" && !config.data) {
      config.data = {};
    }
    return config;
  });

  // 处理响应结果
  responsetUse((response) => {
    return response.data;
  }, handleResponseError);

  return instance;
}

module.exports = { runInterceptors };
